package org.wesc.boot.service.system.dict;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wesc.boot.dao.domain.QueryRequest;
import org.wesc.boot.dao.entity.Dict;
import org.wesc.boot.dao.mapper.DictMapper;
import org.wesc.boot.dao.service.DictService;
import org.wesc.boot.dao.utils.SortUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 字典服务
 *
 * @author Wesley
 * @date 2020-11-24
 */
@Slf4j
@Service
public class DictAdvanceService {

    private final DictMapper dictMapper;

    private final DictService dictService;

    @Autowired
    public DictAdvanceService(DictMapper dictMapper, DictService dictService) {
        this.dictMapper = dictMapper;
        this.dictService = dictService;
    }

    /**
     * 分页查询字典
     */
    public IPage<Dict> pageQueryDictList(QueryRequest request, Dict dict) {
        try {
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();

            if (null != dict.getKeyy()) {
                queryWrapper.eq(Dict::getKeyy, dict.getKeyy());
            }
            if (StringUtils.isNotBlank(dict.getValuee())) {
                queryWrapper.eq(Dict::getValuee, dict.getValuee());
            }
            if (StringUtils.isNotBlank(dict.getTableName())) {
                queryWrapper.eq(Dict::getTableName, dict.getTableName());
            }
            if (StringUtils.isNotBlank(dict.getFieldName())) {
                queryWrapper.eq(Dict::getFieldName, dict.getFieldName());
            }

            Page<Dict> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return dictService.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取字典信息失败", e);
            return null;
        }
    }

    /**
     * 创建字典
     */
    @Transactional(rollbackFor = Exception.class)
    public void createDict(Dict dict) {
        this.dictService.save(dict);
    }

    /**
     * 修改字典
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDict(Dict dict) {
        this.dictMapper.updateById(dict);
    }

    /**
     * 批量删除字典
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteDict(String[] dictIds) {
        if (null == dictIds || dictIds.length == 0) {
            return;
        }
        List<Long> list = new ArrayList<>();
        for(String str : dictIds) {
            list.add(Long.valueOf(str));
        }
        this.dictMapper.deleteBatchIds(list);
    }

}
